<?php

use Illuminate\Support\MessageBag;

class HomeController extends BaseController {

    public function index() {

        return View::make("blank");

        $Options        = Cache::get('options');
        $iCurrentCourse = CNamHoa::CurrentCourse();

        $aData = array(
            'sPage_Title'       => trans('navigation.home'),
            'sPage_Description' => trans('navigation.home-description'),
            'Options'           => $Options,
            'iCurrentCourse'    => $iCurrentCourse,
            'iAuNhi'            => 0,
            'iThieuNhi'         => 0,
            'iNghiaSi'          => 0,
            'iDuBi'             => 0,
        );

        $Classes = Classes::where('course', $iCurrentCourse)
            ->with(['user' => function($query) {
                $query->thieunhi();
            }])
            ->get();

        $ClassesTeam = [];

        foreach ($Classes as $class) {
            @$ClassesTeam[$class->team] += $class->user->count();
        }

        foreach ($ClassesTeam as $key => $value) {

            switch ($key) {
                case 'AU_NHI':
                    $aData['iAuNhi'] = $value;
                    break;

                case 'THI_SINH':
                    $aData['iThieuNhi'] = $value;
                    break;

                case 'NGHIA_SI':
                    $aData['iNghiaSi'] = $value;
                    break;

                case 'QUAN_TRI_DU_BI':
                    $aData['iDuBi'] = $value;
                    break;

                default:
                    break;
            }
        }

        return View::make("home.home", $aData);
    }

    public function login() {
        $errors = new MessageBag();

        if ($old = Input::old("errors")) {
            $errors = $old;
        }

        $data = ["errors" => $errors];

        if (Request::isMethod('post')) {
            $validator = Validator::make(Input::all(), [
                    "username" => "required",
                    "password" => "required"
            ]);
            if ($validator->passes()) {
                $credentials = [
                    "id"       => Input::get("username"),
                    "password" => Input::get("password")
                ];

                $User = User::where('id', Input::get("username"))->quantri()->first();

                $remember = Input::get('remember') ? true : false;

                if (($User && Auth::attempt($credentials, $remember))) {
                    return Redirect::route("home");
                }
            }

            $data["errors"]   = new MessageBag([
                "password" => [trans('login.error-invalid')]
            ]);
            $data["username"] = Input::get("username");
            return Redirect::route("login")->withInput($data);
        }

        return View::make("login", $data);
    }

    public function logout() {
        Auth::logout();
        return Redirect::route("login");
    }

    public function postAjaxAttendance($scoretype) {

        $aData          = $aDays          = $aChart_Data    = [];
        $Options        = Cache::get('options');
        $iCurrentCourse = CNamHoa::CurrentCourse();

        $UserScoreCounter = UserScore::select(['date', 'score', DB::raw("count('user_id') as counter")])
            ->chuyencan((array) $Options['COURSE'][$iCurrentCourse]->data, null)
            ->where('scoretype', $scoretype)
            ->groupBy('date')
            ->groupBy('score')
            ->orderBy('date')
            ->get();

        foreach ($UserScoreCounter as $object) {
            $object->date = CNamHoa::ConvertDate($object->date);

            $aData[$object->score] = [];
            $aDays[$object->date]  = $object->date;
        }

        foreach ($aData as $score => $item) {

            $aChart_Data[$score] = [
                'data'       => [],
                'label'      => isset($Options[$scoretype][$score]) ? $Options[$scoretype][$score]->data->name : $score,
                'lines'      => ['lineWidth' => 1],
                'shadowSize' => 0
            ];

            foreach ($aDays as $date) {
                $aData[$score][$date] = 0;
            }
        }

        foreach ($UserScoreCounter as $object) {
            $aData[$object->score][$object->date] = $object->counter;
        }

        foreach ($aData as $score => $aItemDate) {
            foreach ($aItemDate as $date => $counter) {
                $aChart_Data[$score]['data'][] = [$date, $counter];
            }
        }

        if (!empty($aChart_Data)) {
            $aResponse = [
                'code' => 200,
                'data' => $aChart_Data,
            ];
        } else {
            $aResponse = [
                'code' => 0,
            ];
        }

        return Response::json($aResponse);
    }

    public function postAjaxReview($type) {

        $aData   = [];
        $Options = Cache::get('options');

        $UserIDs = User::select(['id'])
            ->thieunhi()
            ->whereHas('classes', function($q) {
                $q->where('course', CNamHoa::CurrentCourse());
            })
            ->lists('id');

        if (!empty($UserIDs)) {

            switch ($type) {
                case 'attendance':
                    $Counters = DB::table('user_class')->select(['chuyencan', DB::raw("count('user_id') as counter")])
                        ->whereIn('user_id', $UserIDs)
                        ->groupBy('chuyencan')
                        ->get();

                    foreach ($Counters as $object) {
                        $rank = CNamHoa::getChuyenCanRank($object->chuyencan);
                        @$aData[$rank]+=$object->counter;
                    }
                    break;
                case 'score':
                    $Counters = DB::table('user_class')->select(['hocluc', DB::raw("count('user_id') as counter")])
                        ->whereIn('user_id', $UserIDs)
                        ->groupBy('hocluc')
                        ->get();

                    foreach ($Counters as $object) {
                        $rank = CNamHoa::getHocLucRank($object->hocluc);
                        @$aData[$rank]+=$object->counter;
                    }
                    break;
                case 'rank':
                    $Counters = DB::table('user_class')->select(['rank', DB::raw("count('user_id') as counter")])
                        ->whereIn('user_id', $UserIDs)
                        ->groupBy('rank')
                        ->get();

                    foreach ($Counters as $object) {
                        $rank = isset($Options['RANK'][$object->rank]) ? $Options['RANK'][$object->rank]->data : $object->rank;
                        @$aData[$rank]+=$object->counter;
                    }
                    break;

                default:
                    break;
            }
        }

        if (!empty($aData)) {
            foreach ($aData as $key => $data) {
                unset($aData[$key]);
                $aData[] = [
                    'label' => "$key - " . $data,
                    'data'  => $data
                ];
            }

            $aResponse = [
                'code'       => 200,
                'data'       => $aData,
                'element_id' => Input::get("element_id"),
            ];
        } else {
            $aResponse = [
                'code' => 0,
            ];
        }

        return Response::json($aResponse);
    }

    public function postAjaxSearchBox() {
        $searchKey = Input::get('searchKey');
        $Users     = User::where('id', 'like', '%' . $searchKey . '%')
            ->orWhere('username', 'like', '%' . $searchKey . '%')
            ->limit(10)
            ->get();

        $aResponse = [];

        if (!empty($Users)) {
            foreach ($Users as $user) {
                $aResponse[] = [
                    'name'      => "$user->id - $user->username",
                    'data-href' => route('profile', ['id' => $user->id]),
                ];
            }
        }

        return Response::json($aResponse);
    }

}
